package com.summerbird.mallchat.common.chat.service.strategy.frequency;

import com.summerbird.mallchat.common.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 固定窗口限流算法实现
 */
@Slf4j
@Component
public class FixWindowFrequencyStrategy extends AbstractFrequencyControlStrategy <FrequencyControlDTO>{

    @Override
    protected boolean reachRateLimit(Map<String, FrequencyControlDTO> frequencyControlMap) {
        // 批量查询redis
        ArrayList<String> keyList = new ArrayList<>(frequencyControlMap.keySet());
        List<Integer> countList = RedisUtils.mget(keyList, Integer.class);
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            Integer count = countList.get(i);
            FrequencyControlDTO frequencyControlDTO = frequencyControlMap.get(key);
            if(Objects.nonNull(count) && count >= frequencyControlDTO.count){
                //频率超过了
                log.warn("frequencyControl limit key:{},count:{}", key, count);
                return true;
            }
        }
        return false;
    }

    @Override
    protected void addFrequencyControlStatisticsCount(Map<String, FrequencyControlDTO> frequencyControlMap) {
        frequencyControlMap.forEach((k, v) -> {
            RedisUtils.inc(k, v.time, v.unit);
        });
    }

    @Override
    protected String getStrategyName() {
        return FrequencyStrategyType.FIXWINDOW.getName();
    }
}
